const express = require("express");
const Code = require("./verification-code");
const Send = require("./utils/Send");
const Utils = require("./utils");
const Redis = require("./utils/Redis");
const Token = require("./utils/Token");
const { ActivityLogs } = require("./models");
const router = express.Router();


// 需要校验图形验证码的接口名单
const codePathList = ["/user/account/accountSignin", "/user/account/accountLogin"];
// 无需登录的接口名单
const noAuthPathList = [
  // 发送验证码接口
  "/code",
  "/emailCode",
  "/smsCode",

  "/user/account/isAccountCanSignup", // 账号是否可注册
  "/user/account/accountSignin", // 账号注册
  "/user/account/accountLogin", // 账号登录
];

/**
 * 路由拦截器中间件
 */
async function checkAuth(req, res, next) {
  try {
    // 获取客户基本参数
    const { token, client_uuid, client_ip, user_agent } = Utils.getBaseParams(req);
    // 获取请求路径
    const path = req.path;
    console.log("----path----", path);
    // 判断是否需要验证码
    if (codePathList.includes(path)) {
      // 从请求体中获取uuid和code
      const { uuid, code } = req.body;
      // 判断uuid和code是否存在
      if (!uuid || !code) {
        res.send(Send.fail("验证码不能为空"));
        return;
      }
      // 判断验证码是否正确
      const isCodeCorrect = await Code.checkCode(client_uuid, uuid, code);
      if (!isCodeCorrect) {
        res.send(Send.fail("验证码错误"));
        return;
      }
    }
    // 判断是否需要登录
    if (!noAuthPathList.includes(path)) {
      // 判断token是否存在
      if (!token) {
        res.send(Send.fail("token不能为空", 401));
        return;
      }
      // 验证token
      const info = await Token.getInfoByToken(token);
      // 更新token有效期
      await Token.updateExpire(token);
      // 添加操作日志
      await ActivityLogs.create({ user_id: info.id, path, client_ip, user_agent })
    }
    next();
  } catch (error) {
    res.send(Send.fail(error, 500));
  }
}

/**
 * 注册路由
 */
router.use("/", checkAuth, require("./routers/index"));

module.exports = router;
